using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiWrite.Application.Command;

namespace WMS.WebApiWrite.Application.Commandhandler
{
    /// <summary>
    /// 删除仓库信息命令处理器（逻辑删除）
    /// </summary>
    public class DeleteWarehouseCommandHandler : IRequestHandler<DeleteWarehouseCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;

        /// <summary>
        /// 构造函数，注入仓库仓储
        /// </summary>
        public DeleteWarehouseCommandHandler(IBaseRepository<WarehouseInfo> warehouseRepository)
        {
            this.warehouseRepository = warehouseRepository;
        }

        /// <summary>
        /// 处理删除仓库信息命令（逻辑删除）
        /// </summary>
        public async Task<ApiResult<bool>> Handle(DeleteWarehouseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询仓库信息（只查询未删除的记录）
                var warehouseInfo = warehouseRepository.GetAll()
                    .Where(x => !x.IsDeleted)
                    .FirstOrDefault(x => x.WarehouseID == request.WarehouseID);

                if (warehouseInfo == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.删除失败,
                        Message = "仓库信息不存在",
                        Data = false
                    };
                }

                // 逻辑删除：设置删除标记和删除信息
                warehouseInfo.IsDeleted = true;
                warehouseInfo.DeleteName = request.OperatorName;
                warehouseInfo.DeleteTime = DateTime.Now;

                // 执行更新操作（逻辑删除使用UpdateAsync而非Delete）
                var result = await warehouseRepository.UpdateAsync(warehouseInfo);

                if (result > 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.删除成功,
                        Message = "删除仓库信息成功",
                        Data = true
                    };
                }
                else
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.删除失败,
                        Message = "删除仓库信息失败",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiResultEnum.删除失败,
                    Message = $"删除仓库信息异常：{ex.Message}",
                    Data = false
                };
            }
        }
    }
}

